package com.wx.mall.goods.controller;


import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageInfo;
import com.wx.mall.common.utils.WebTools;
import com.wx.mall.goods.entity.Album;
import com.wx.mall.goods.service.IAlbumService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author j
 * @since 2020-03-15
 */
@RestController
@RequestMapping("/album")
@Api(tags = "图片相册相关接口")
public class AlbumController {

    @Value("${localhost.file.path}")
    private String filePath;
    @Autowired
    private IAlbumService IAlbumService;

    @ApiOperation("分页查询图片相册列表")
    @GetMapping("/page")
    public Map<String,Object> page(@ApiParam("页大小") String pageSize,@ApiParam("页码")  String pageNum,@ApiParam("标题")  String title,@ApiParam("排序")  String sort){
        if(StringUtils.isEmpty(pageSize)){
            pageSize="10";
        }
        if(StringUtils.isEmpty(pageNum)){
            pageNum="1";
        }
        Album album = new Album();
        album.setTitle(title);
        album.setImageNum(sort);
        return WebTools.returnDate(IAlbumService.find(album,Integer.valueOf(pageSize),Integer.valueOf(pageNum)),200);
    }

    @ApiOperation("查询全部图片相册列表")
    @GetMapping("/findAll")
    public Map<String,Object> findAll(){
        return WebTools.returnDate(IAlbumService.findAll(),200);
    }

    @ApiOperation("按id查询图片相册列表")
    @PostMapping("/findById")
    public Map<String,Object> findById(@ApiParam("图片相册id") String id){
        Album album = new Album();
        album.setId(Integer.valueOf(id));
        return WebTools.returnDate(IAlbumService.find(album,1,1).getList().get(0).getImageItems(),200);
    }

    @ApiOperation("按id删除图片相册")
    @GetMapping("/deletes")
    public Map<String,Object> deletes(@ApiParam("图片相册ids") String ids){
        IAlbumService.deletes(ids);
        return WebTools.returnDate("删除成功！",200);
    }

    @ApiOperation("保存和更新图片相册")
    @PostMapping("/form")
    public Map<String,Object> form(@RequestParam(value = "file",required = false) @ApiParam("上传的文件") MultipartFile file, HttpServletRequest req,@ApiParam("相册id") String id, @ApiParam("标题") String title, @ApiParam("序号") String sort, @ApiParam("描述") String instruction) throws IOException {
        Album album = new Album();
        album.setTitle(title);
        album.setSort(Integer.valueOf(sort));
        album.setInstruction(instruction);
        album.setImageItems("");
        album.setImageNum("0");
        if(id.equals("undefined")){
            id="";
        }
        if(!StringUtils.isEmpty(id)) {
            album.setId(Integer.valueOf(id));
        }
        if(file != null){
            String imgId = WebTools.getRandomID()+".png";
            WebTools.cacheFile(file,filePath,imgId);
            album.setImage("/showImg?id="+imgId+"&token=0");
        }else{
            if(!StringUtils.isEmpty(id)){
                Album album1 = new Album();
                album.setId(Integer.valueOf(id));
                PageInfo<Album> pageInfo = IAlbumService.find(album1,1,1);
                if(pageInfo.getTotal()>0){
                    album.setImage(pageInfo.getList().get(0).getImage());
                    album.setImageItems(pageInfo.getList().get(0).getImageItems());
                }
            }else{
                album.setId(Integer.valueOf(id));
            }
        }
        if(StringUtils.isEmpty(id)){
            IAlbumService.save2(album);
            return WebTools.returnDate("保存成功！",200);
        }else{
            IAlbumService.update(album);
            return WebTools.returnDate("更新成功！",200);
        }
    }

    @ApiOperation("上传相册图片")
    @PostMapping("/uploadImg")
    public Map<String,Object> uploadImg(@RequestParam(value = "file",required = false) @ApiParam("上传的文件") List<MultipartFile> file, HttpServletRequest req, @ApiParam("相册id") String id) throws IOException {
        Album album = new Album();
        album.setId(Integer.valueOf(id));
        PageInfo<Album> page = IAlbumService.find(album,1,1);
        if(page.getTotal()>=1){
            String imgs = "";
            for(int i=0;i<file.size();i++){
                String imgId = WebTools.getRandomID()+".png";
                WebTools.cacheFile(file.get(i),filePath,imgId);
                imgs+="/showImg?id="+imgId+"&token=0,";
            }
            album = page.getList().get(0);
            album.setImageItems(album.getImageItems()+imgs);
            album.setImageNum(String.valueOf(album.getImageItems().split(",").length));
            if(StringUtils.isEmpty(album.getImageItems())){
                album.setImageNum("0");
            }
            IAlbumService.update(album);
            return WebTools.returnDate(album.getImageItems(),200);
        }
        return WebTools.returnDate("上传失败！",200);
    }

    @ApiOperation("转移图片")
    @PostMapping("/updateImg")
    public Map<String,Object> updateImg(@ApiParam("相册id") String id, @ApiParam("转移图片地址") String imgPath) {
        Album album = new Album();
        album.setId(Integer.valueOf(id));
        Album album2 = new Album();
        album2.setImageItems(imgPath);
        PageInfo<Album> page2 = IAlbumService.find(album2,1,1);
        if(page2.getTotal()>=1){
            album2 = page2.getList().get(0);
            String[] imgs = album2.getImageItems().split(",");
            String imgss = "";
            for(int i=0;i<imgs.length;i++){
                if(!(imgs[i]+",").equals(imgPath+",")){
                    imgss+=imgs[i]+",";
                }
            }
            album2.setImageItems(imgss);
            album2.setImageNum(String.valueOf(album2.getImageItems().split(",").length));
            if(StringUtils.isEmpty(imgss)){
                album2.setImageNum("0");
            }
            IAlbumService.update(album2);

            PageInfo<Album> page = IAlbumService.find(album,1,1);
            album = page.getList().get(0);
            album.setImageItems(album.getImageItems()+imgPath+",");
            album.setImageNum(String.valueOf(album.getImageItems().split(",").length));
            if(StringUtils.isEmpty(album.getImageItems())){
                album.setImageNum("0");
            }
            IAlbumService.update(album);

            return WebTools.returnDate(album2.getImageItems(),200);
        }
        return WebTools.returnDate("转移失败！",200);
    }

    @ApiOperation("删除图片")
    @PostMapping("/deleteImg")
    public Map<String,Object> deleteImg(@ApiParam("相册id") String id, @ApiParam("图片地址") String imgs) {
        Album album = new Album();
        album.setId(Integer.valueOf(id));
        PageInfo<Album> page = IAlbumService.find(album,1,1);
        if(page.getTotal()>=1){
            album = page.getList().get(0);
            String[] imgss = imgs.split(",");
            String[] albums = album.getImageItems().split(",");
            String img="";
            for (int i=0;i<albums.length;i++){
                boolean isSave = true;
                for (int j=0;j<imgss.length;j++){
                    if(albums[i].equals(imgss[j])){
                        isSave=false;
                        break;
                    }
                }
                if(isSave){
                    img+=albums[i]+",";
                }
            }
            album.setImageItems(img);
            album.setImageNum(String.valueOf(album.getImageItems().split(",").length));
            if(StringUtils.isEmpty(img)){
                album.setImageNum("0");
            }
            IAlbumService.update(album);
            return WebTools.returnDate(album.getImageItems(),200);
        }
        return WebTools.returnDate("删除失败！",200);
    }

    @GetMapping("/showImg")
    public void showImg(String id,HttpServletResponse response) {
        FileInputStream in = null;
        OutputStream os = null;
        String url= filePath+id;
        File file = new File(url);
        try{
//            if(file.exists()) {
                in = new FileInputStream(file);
                os = response.getOutputStream();
                byte[] b = new byte[1024];
                while(in.read(b)!= -1) {
                    os.write(b);
                }
//            }

        }catch (Exception e){}finally {
            try{
                if(in != null){
                    in.close();
                }
                if(os != null){
                    os.flush();
                    os.close();
                }
            }catch (Exception e){}
        }
    }
}

